<template>
  <div class="questions-container">
    <div class="header">
      <h1>问答社区</h1>
      <p>在这里提问和回答问题，与大家一起交流学习</p>
    </div>

    <!-- 操作区域 -->
    <div class="actions-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索问题..."
            clearable
            @keyup.enter="searchQuestions"
          >
            <template #append>
              <el-button :icon="Search" @click="searchQuestions" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button
            type="primary"
            :icon="Plus"
            @click="askQuestion"
          >
            提出问题
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select
            v-model="selectedCourse"
            placeholder="选择课程"
            clearable
            @change="filterQuestions"
            filterable
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.title"
              :value="course.id"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="selectedStatus"
            placeholder="问题状态"
            clearable
            @change="filterQuestions"
          >
            <el-option label="开放" value="OPEN" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已关闭" value="CLOSED" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="sortBy"
            placeholder="排序方式"
            @change="sortQuestions"
          >
            <el-option label="最新发布" value="createTime,desc" />
            <el-option label="最多回答" value="answerCount,desc" />
            <el-option label="最多浏览" value="viewCount,desc" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <div class="filter-summary" v-if="selectedCourse || selectedStatus">
            <el-tag
              v-if="selectedCourse"
              closable
              @close="clearCourseFilter"
            >
              课程: {{ getCourseTitle(selectedCourse) }}
            </el-tag>
            <el-tag
              v-if="selectedStatus"
              closable
              @close="clearStatusFilter"
              :type="getQuestionStatusType(selectedStatus)"
            >
              状态: {{ getQuestionStatusText(selectedStatus) }}
            </el-tag>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 问题列表 -->
    <div class="questions-list">
      <el-card
        v-for="question in questions"
        :key="question.id"
        class="question-card"
        shadow="hover"
        @click="viewQuestion(question.id)"
      >
        <div class="question-header">
          <h3 class="question-title">{{ question.title }}</h3>
          <div class="question-status">
            <el-tag
              :type="getQuestionStatusType(question.status)"
              size="small"
            >
              {{ getQuestionStatusText(question.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="question-content">
          <p>{{ question.content }}</p>
        </div>
        
        <div class="question-meta">
          <div class="meta-item">
            <el-icon><User /></el-icon>
            <span>{{ question.userName }}</span>
          </div>
          <div class="meta-item">
            <el-icon><Clock /></el-icon>
            <span>{{ formatDate(question.createTime) }}</span>
          </div>
          <div class="meta-item">
            <el-icon><View /></el-icon>
            <span>{{ question.viewCount }} 浏览</span>
          </div>
          <div class="meta-item">
            <el-icon><ChatLineRound /></el-icon>
            <span>{{ question.answerCount }} 回答</span>
          </div>
          <div v-if="question.courseTitle" class="meta-item">
            <el-icon><Collection /></el-icon>
            <span>{{ question.courseTitle }}</span>
          </div>
        </div>
      </el-card>
      
      <div v-if="questions.length === 0" class="no-questions">
        <el-icon><ChatLineRound /></el-icon>
        <p>暂无问题</p>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalQuestions"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Search,
  Plus,
  User,
  Clock,
  View,
  ChatLineRound,
  Collection
} from '@element-plus/icons-vue'
import request from '../../utils/request'

// 路由
const router = useRouter()

// 数据
const questions = ref([])
const courses = ref([])
const searchKeyword = ref('')
const selectedCourse = ref('')
const selectedStatus = ref('')
const sortBy = ref('createTime,desc')
const currentPage = ref(1)
const pageSize = ref(10)
const totalQuestions = ref(0)

// 获取问题列表
const fetchQuestions = async () => {
  try {
    // 构建查询参数，只包含有值的参数
    const params: any = {
      page: currentPage.value - 1,
      size: pageSize.value,
      sort: sortBy.value
    }
    
    // 只有当值不为空时才添加到参数中
    if (selectedCourse.value) {
      params.courseId = selectedCourse.value
    }
    
    if (selectedStatus.value) {
      params.status = selectedStatus.value
    }
    
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    const response = await request.get('/api/study/questions', {
      params
    })
    
    questions.value = response.data.content
    totalQuestions.value = response.data.totalElements
  } catch (error) {
    ElMessage.error('获取问题列表失败')
  }
}

// 获取课程列表
const fetchCourses = async () => {
  try {
    const response = await request.get('/api/study/courses/published', {
      params: {
        page: 0,
        size: 100
      }
    })
    courses.value = response.data.content
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 搜索问题
const searchQuestions = () => {
  currentPage.value = 1
  fetchQuestions()
}

// 筛选问题
const filterQuestions = () => {
  currentPage.value = 1
  fetchQuestions()
}

// 排序问题
const sortQuestions = () => {
  currentPage.value = 1
  fetchQuestions()
}

// 清除课程筛选条件
const clearCourseFilter = () => {
  selectedCourse.value = ''
  filterQuestions()
}

// 清除状态筛选条件
const clearStatusFilter = () => {
  selectedStatus.value = ''
  filterQuestions()
}

// 获取课程标题
const getCourseTitle = (courseId: string) => {
  const course = courses.value.find((c: any) => c.id === Number(courseId))
  return course ? course.title : ''
}

// 查看问题详情
const viewQuestion = (questionId: number) => {
  router.push(`/study/questions/${questionId}`)
}

// 提出问题
const askQuestion = () => {
  router.push('/study/questions/ask')
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchQuestions()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchQuestions()
}

// 工具方法
const getQuestionStatusType = (status: string) => {
  switch (status) {
    case 'OPEN':
      return 'primary'
    case 'RESOLVED':
      return 'success'
    case 'CLOSED':
      return 'info'
    default:
      return 'info'
  }
}

const getQuestionStatusText = (status: string) => {
  switch (status) {
    case 'OPEN':
      return '开放'
    case 'RESOLVED':
      return '已解决'
    case 'CLOSED':
      return '已关闭'
    default:
      return '未知'
  }
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchQuestions()
  fetchCourses()
})
</script>

<style scoped>
.questions-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.header {
  margin-bottom: 30px;
}

.header h1 {
  color: #303133;
  margin-bottom: 10px;
}

.header p {
  color: #606266;
  margin: 0;
}

.actions-section {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-right {
  text-align: right;
}

.filter-section {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-summary {
  display: flex;
  gap: 10px;
  align-items: center;
  height: 100%;
}

.questions-list {
  margin-bottom: 30px;
}

.question-card {
  margin-bottom: 20px;
  cursor: pointer;
}

.question-card:hover {
  border-color: #409eff;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.question-title {
  margin: 0;
  color: #303133;
  font-size: 18px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.question-status {
  flex-shrink: 0;
  margin-left: 15px;
}

.question-content {
  margin-bottom: 20px;
}

.question-content p {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.question-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.no-questions {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

.no-questions .el-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>